<template>
  <div class="slideBar">
    <div class="progress">
      <div class="active" :style="{width:activeWidth+'%'}">
        <div class="slide" @touchstart="touch" ref="slideBtn">
      </div>
    </div>
    </div>
  </div>
</template>

<script>
export default {
  name:'Slide',
  props:['step', 'min', 'max', 'value'],
  data (){
    return {

    }
  },
  mounted (){

  },
  methods: {
    // 计算双向绑定的值时,不要自身操作赋值给自身,会进行无限递增
    touch (e){
      this.startX = e.touches[0].pageX
      this.w = e.path[1].offsetWidth
      this.pw = e.path[2].offsetWidth
      this.$refs.slideBtn.addEventListener('touchmove', this.touchmove, false)
      this.$refs.slideBtn.addEventListener('touchend', this.touchend, false)
    },
    touchmove (e){
      const current = e.touches[0].pageX
      const move = current - this.startX
      let percent = (this.w + move) / this.pw
      if (percent > 1) percent = 1
      if (percent < 0) percent = 0
      let fontSize = this.min + percent * (this.max - this.min)
      fontSize = fontSize.toFixed(1)
      if (fontSize % this.step === 0) this.$emit('input', fontSize + 'px')
    },
    touchend (e){
      this.$refs.slideBtn.removeEventListener('touchmove', this.touchmove)
    }
  },
  computed: {
    activeWidth (){
      // 将'12px' 转换为数字 12
      const value = +this.value.slice(0, -2)
      if (value > this.max) return 100
      if (value < this.min) return 0
      return (value - this.min) / (this.max - this.min) * 100
    },
    blockNum (){
      return (this.max - this.min) / this.step
    }
  }
}
</script>

<style lang="less" scoped>
.slideBar{
  width: 100%;
  padding: 20px;
  height: 0.2em;
  line-height: 1.5em;
  background-color: transparent;
  .progress{
    width: 100%;
    height: .2em;
    background-color: var(--box-bg);
  }
  .active{
    background-color: var(--font-active-color);
    width: 50%;
    height: 100%;
    position: relative;
    // transition: width 200s linear;
    .slide{
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      transform: translateX(50%);
      margin: auto 0;
      background-color: var(--box-bg);
      width: 1.5em;
      height: 0.8em;
      border-radius: .1em;
    }

  }
}
</style>>
